package com.blast.sspai.util;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

/**
 * Created by kHRYSTAL on 2015/6/15.
 */

/**
 * 该类为通用工具类 用于向服务器发起请求并获取Json字符串
 */
public final class CommonUtiles {

    /**
     * 向服务器发起get请求获取json
     * @param url 请求的url
     * @return 服务器响应json字符串
     */
    public static String doGet(String url) {
        String jsonStr = null;
        InputStream is = null;
        byte[] b = null;

        try {
            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setReadTimeout(4000);
            Log.d("Response",""+conn.getResponseCode());
            if (conn.getResponseCode()==200){
                is = conn.getInputStream();
                b = streamToByte(is);
                jsonStr = new String(b,"utf-8");
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        return jsonStr;
    }

    /**
     * 将输入流转换为字节数组 用于读取图片和Json字符串等
     * @param inputStream url读取的输入流
     * @return 字节数组
     * @throws java.io.IOException
     */
    public static byte[] streamToByte(InputStream inputStream) throws IOException {
        byte[] ret = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len=inputStream.read(buf)) != -1){
            baos.write(buf,0,len);
        }
        buf = null;
        ret = baos.toByteArray();

        baos.close();
        return ret;
    }


    /**
     * 进行网络Post请求的方式 参数采用Key-value的形式
     * @param url
     * @param params
     * @return
     */
    public static byte[] doPost(String url,HashMap<String,String> params){
        return null;
    }

    /**
     * 进行PUT请求的方法，实际的操作和Post类似
     * @param url
     * @param params
     * @return
     */
    public static byte[] doPut(String url,HashMap<String,String> params){
        return null;
    }

    /**
     * 进行Delete请求的方法 实际的操作和GET类似
     * @param url
     * @return
     */
    public static byte[] doDelete(String url){
        return null;
    }
}
